﻿using System;
using System.IO;

namespace SharpDepend.WPF
{
    class FileManager : IFileManagerManager
    {
        private string[] EmptyStringArray = new string[0];

        public bool PathExist(string path, bool directory)
        {
            if (directory)
            {
                return Directory.Exists(path);
            }
            else
            {
                return File.Exists(path);
            }
        }

        public void CreateFolder(string path)
        {
            Directory.CreateDirectory(path);
        }

        public Stream CreateFile(string path)
        {
            return File.Create(path);
        }

        public Stream OpenFile(string path)
        {
            return File.Open(path, FileMode.Open);
        }

        public string[] ListFiles(string folderPath)
        {
            try
            {
                return Directory.GetFiles(folderPath);
            }
            catch (Exception)
            {
                return EmptyStringArray;
            }
        }

        public string[] ListFolders(string folderPath)
        {
            try
            {
                return Directory.GetDirectories(folderPath);
            }
            catch (Exception)
            {
                return EmptyStringArray;
            }
        }

        public void CopyFile(Stream stream, string destinationPath)
        {
            using (var streamDestination = CreateFile(destinationPath))
            {
                const int SIZE = 1024;
                byte[] buffer = new byte[SIZE];
                int read = SIZE;
                while (read == SIZE)
                {
                    read = stream.Read(buffer, 0, SIZE);
                    streamDestination.Write(buffer, 0, read);
                }
            }
        }

        public void MoveFile(string sourcePath, string destinationPath)
        {
            File.Move(sourcePath, destinationPath);
        }

        public void DeleteFile(string filePath)
        {
            File.Delete(filePath);
        }

        public void DeleteFolder(string folderPath)
        {
            Directory.Delete(folderPath);
        }

        public string[] GetDrives(DriveType driveType)
        {
            switch (driveType)
            {
                case DriveType.Logical:
                    return Directory.GetLogicalDrives();
                case DriveType.Special:
                    return new string[0];
                case DriveType.All:
                    return Directory.GetLogicalDrives();
                default:
                    throw new NotImplementedException(driveType.ToString());
            }
        }
    }
}